import { LocalCache } from '@/utils/front/storage';
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';

const initialState = {
  userInfo: {
    name: 'lufyKKKK',
  } as UserInfo,
  todos: [] as any[],
};

const getTokenAction = createAsyncThunk(
  'getToken',
  async (value: { code: string }) => {
    const result = { access_token: value.code };
    return result;
  }
);

const userStore = createSlice({
  name: 'user',
  initialState,
  reducers: {
    initUserState(state, action) {
      Object.assign(state, action.payload);
    },
    setUserInfo(state, action) {
      state.userInfo = action.payload;
      // const LCache = LocalCache();
      // LCache.set('user', state.userInfo);
    },
    restoreUserInfo(state, action) {
      const LCache = LocalCache();
      const userInfo = LCache.get<UserInfo | null>('user');
      if (!userInfo) return;
      state.userInfo = userInfo;
    },
    clearUserInfo(state, action) {
      const LCache = LocalCache();
      LCache.del('user');
      state.userInfo = {} as UserInfo;
    },
    setToken(state, action) {
      state.userInfo = { ...state.userInfo, accessToken: action.payload };
    },
  },
  extraReducers(builder) {
    builder.addCase(getTokenAction.fulfilled, (state, action) => {
      const token = action.payload?.access_token;
      state.userInfo = {
        ...state.userInfo,
        accessToken: token,
      };
    });
  },
});

const userOtherActions = {
  getToken: getTokenAction,
};

export { userOtherActions };

export default userStore;
